package com.qiangzi.workflow.engine.core;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.core.io.Resource;

import com.qiangzi.workflow.engine.bpmn.base.ProcessDefinition;
import com.qiangzi.workflow.engine.bpmn.base.ProcessInstance;
import com.qiangzi.workflow.engine.service.RepositoryService;
import com.qiangzi.workflow.engine.service.RuntimeService;
import com.qiangzi.workflow.engine.service.XmlParserService;
import com.qiangzi.workflow.engine.service.impl.Dom4JXmlParserService;
import com.qiangzi.workflow.engine.service.impl.MemoryRepositoryService;
import com.qiangzi.workflow.engine.service.impl.MemoryRuntimeService;

import lombok.Data;

@Data
public class MyEngine implements Engine {

	// private static MyEngine INSTANCE = new MyEngine();

	private XmlParserService xmlParserService;
	private RepositoryService repositoryService;
	private RuntimeService runtimeService;
	// 缓存一份解析定义
	private Map<String, ProcessDefinition> parsedProcessDefinitions = new ConcurrentHashMap<String, ProcessDefinition>();

	public MyEngine() {

		xmlParserService = new Dom4JXmlParserService();
		repositoryService = new MemoryRepositoryService();
		runtimeService = new MemoryRuntimeService();

	}

	@Override
	public ProcessDefinition parse(Resource resource) throws Exception {

		ProcessDefinition processDefinition = xmlParserService.parse(resource);
		// 这里是覆盖
		parsedProcessDefinitions.put(processDefinition.getId(), processDefinition);
		return processDefinition;

	}

	@Override
	public ProcessInstance deploy(ProcessDefinition processDefinition) throws Exception {

		return repositoryService.deploy(processDefinition);

	}

	@Override
	public void run(ProcessInstance processInstance) throws Exception {

		this.runtimeService.run(processInstance, this);

	}

}